/*
 * Copyright (C) 2012 VinaVAC. All rights reserved.
 */
package org.vinavac.bean;

import javax.annotation.Resource;
import javax.ejb.LocalBean;
import javax.ejb.SessionContext;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.vinavac.entity.Staff;

/**
 *
 * @author Quang <quangtin3@gmail.com>
 */
@Stateless
@LocalBean
public class StaffSessionBean extends AbstractSessionBean<Staff> {

    @PersistenceContext(unitName = VINAVAC_PERSISTENCE_UNIT_NAME)
    private EntityManager em;
    @Resource
    private SessionContext sessionContext;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public StaffSessionBean() {
        super(Staff.class);
    }

    public Staff getStaffByEmail(String email) {
        Query query = em.createNamedQuery("Staff.findByEmail");
        query.setParameter("email", email);
        Staff staff = (Staff) query.getSingleResult();
        return staff;
    }

    /**
     * get login username from application server jdbc-realm, ANONYMOUS if not
     * logged in
     *
     * @return email address of logged in user. (username == email address)
     */
    public String getUsername() {
        return sessionContext.getCallerPrincipal().getName();
    }

    /**
     * Get current logged in staff.
     *
     * @return logged in staff object
     */
    public Staff getStaff() {
        return getStaffByEmail(getUsername());
    }
}
